import TauTable from '@/components/TauTable';
import { toJS } from 'mobx';
import React, { useCallback, useEffect, useState } from 'react';
import { column, orderModel } from '../stores/definitions';
import { t } from '@lingui/macro';
import { Button, Dialog, Message } from '@alifd/next';
import { useStore } from '@/hooks';
import QR from '@/components/QR/QR';

function TicketTable(props) {
  const { scOrder, inForm = false, isViewMode, refundInfo = [], orderId } = props;
  const { scOrderStore: store } = useStore();
  const [ticketInfo, setTicketInfo] = useState([]);
  const [QRModal, setQRModal] = useState({});
  const { companies, baseUrl, imgUrl } = global.getEnvCfg() || {};

  useEffect(() => {
    (async () => {
      const res = await store.get(orderId);
      setTicketInfo(res?.scOrder?.ticketInfo);
    })();
  }, [props]);

  const reqRefundTickets = getRefundingTicket(refundInfo);

  const subModel = orderModel.scOrder.ticketInfo[0];
  const mapper = useCallback((row, idx) => {
    const matchRefundInfo = reqRefundTickets.find(({ ticketCode }) => ticketCode === row.ticketCode) || {};
    const isRefunding = !_.isEmpty(matchRefundInfo);
    return {
      ...row,
      id: `${row.ticketCode}-${idx}`,
      // ticketTime: scOrder?.shiftTime,
      isRefunding,
    };
  });

  // 获取更多列
  const getMoreColumns = () => {
    const res = [
      {
        title: t`报备退款`,
        width: 100,
        cell: (_, __, record) => {
          const { report: value } = record;
          let text;
          if (value) {
            text = t`撤销`;
          } else {
            text = t`报备`;
          }
          return (
            <Button
              text
              type="primary"
              style={{ color: value ? 'red' : '' }}
              onClick={() => handleReportRefund(record, text)}
            >
              {text}
            </Button>
          );
        },
      },
    ];
    if (companies.ZL.id === scOrder?.companyId) res.shift();
    return res;
  };

  /**
   * 报备退款
   * @param {*} r
   */
  const handleReportRefund = (r, text) => {
    const args = {
      type: r.report ? 0 : 1,
      orderType: 2,
      ticketCode: r.operatingTicketCode,
      orderId,
    };
    Dialog.confirm({
      title: t`确定要${text}吗?`,
      onOk: async () => {
        try {
          await store.reportTicket(args);
          Message.success({ content: t`${text}成功` });
        } catch (error) {
          Message.error({ content: t`${text}失败`, duration: 7000 });
        }
      },
    });
  };

  // 获取正在申请退款的车票
  function getRefundingTicket(data) {
    const refundsInfo = _.cloneDeep(data) || [];
    if (refundsInfo.length <= 0) return [];

    const allTicket = refundsInfo?.reduce((res, cur) => {
      const { type, ticketRefundInfos = [] } = cur;
      if (type !== '1') {
        res.push(...ticketRefundInfos);
      }
      return res;
    }, []);
    return allTicket;
  }


  // 扫码绑定用户
  const handleQrCode = async (v, r) => {
    try {
      const { passengerName } = scOrder;
      const text = encodeURIComponent(`${imgUrl}/mp/?text=${v}`);
      const url = `${baseUrl}/api/files/qrcode?text=${text}&height=300&width=300`;
      setQRModal({
        open: true,
        name: passengerName,
        baseUrl: url,
        okText: '下载',
        onCancel: QROnCancel,
      });
    } catch (error) {
      console.log('🚀 _ file: TicketTable.jsx:123 _ error:', error);
    }
  };

  // 关闭二维码
  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  return (
    <div style={{ padding: inForm ? '' : '20px 0 20px 60px' }}>
      <TauTable
        size={inForm ? 'small' : 'medium'}
        hidePagination
        dataSource={toJS(ticketInfo.map(mapper))}
        primaryKey="id"
        columns={[
          column('ticketCode', { width: 208 }, subModel),
          column('seats', { width: 78 }, subModel),
          column('scTicketType', { width: 118 }, subModel),
          column('shiftTime', { width: 168 }, subModel),
          column('stateName', { width: 138 }, subModel),
        ].concat(scOrder?.companyId === 'platform' ? [] : [
          column('operatingTakeTicketCode', {
            width: 128,
            cell: (v, i, r) => {
              if (companies.ZL.id === scOrder?.companyId) {
                return <Button type="primary" text onClick={() => handleQrCode(v, r)}>{t`查看取票码`}</Button>;
              }
              return <>{v || r.ticketCode}</>;
            },
          }, subModel),
          column('operatingState', { width: 128 }, subModel),
          column('refundInfos[0].operatorRefundTime', { width: 124 })])}
      />
      <QR modal={QRModal} />
    </div>
  );
}
export default TicketTable;
